package vip.youngboy.freejump.service.model;

import com.google.common.collect.Lists;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.SubProcess;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BpmnModelService {

    @Autowired
    private ProcessEngineConfiguration processEngineConfiguration;

    @Autowired
    private ProcessEngine processEngine;

    public BpmnModel getBpmnModel(String proDefId) {
        BpmnModel bpmnModel = processEngine.getRepositoryService().getBpmnModel(proDefId);
        return bpmnModel;
    }

    public List<UserTask> getAllTaskElement(String proDefId) {
        BpmnModel bpmnModel = getBpmnModel(proDefId);
        Collection<FlowElement> flowElements = bpmnModel.getMainProcess().getFlowElements();
        List<UserTask> allElements = getChildrenElement(flowElements);
        return allElements;
    }


    public List<UserTask> getChildrenElement(Collection<FlowElement> flowElements) {
        List<UserTask> userTasks = Lists.newArrayList();
        for (FlowElement flowElement : flowElements) {
            if (flowElement instanceof SubProcess) {
                //递归获取任务节点
                Collection<FlowElement> subFlows = ((SubProcess) flowElement).getFlowElements();
                List<UserTask> childrenElement = getChildrenElement(subFlows);
                userTasks.addAll(childrenElement);
            } else if (flowElement instanceof UserTask) {
                UserTask userTask = (UserTask) flowElement;
                userTasks.add(userTask);
            }
        }
        return userTasks;
    }

    public List<UserTask> filterUserTask(List<FlowElement> flowElements) {
        return flowElements.stream().filter(item -> item instanceof UserTask).map(userTask -> (UserTask) userTask).collect(Collectors.toList());
    }

}
